import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../global/Global.dart';
import '../main.dart';
import '../model/LoginModel.dart';

class LoginViewModel extends ChangeNotifier {
  // late TextEditingController _user;
  // late TextEditingController _pass;

  void login({required String username, required String password}) async {
    var res = await loginModel(username: username, password: password);
    SharedPreferences sp = await SharedPreferences.getInstance();
    // print(res);
    if (res.data['success']) {
      Global().getInstance().token = res.data["data"]["token"];
      Global().getInstance().user = res.data["data"]["user"];
      sp.setString("token", res.data["data"]["token"]);
      Global().getInstance().dio.options.headers["token"] =
          res.data["data"]["token"];
      Navigator.popAndPushNamed(
          navigatorKey.currentContext as BuildContext, '/menu');
      // Navigator.of(navigatorKey.currentContext as BuildContext).pushNamed('/menu');
    } else {
      EasyLoading.showError(res.data['msg']);
    }
  }

  void tokenLogin(String token) async {
    SharedPreferences sp = await SharedPreferences.getInstance();
    Response result = await tokenLoginModel();
    if (result.data["success"]) {
      Global().getInstance().user = result.data["data"];
      Navigator.of(navigatorKey.currentContext as BuildContext)
          .popAndPushNamed("menu");
    } else {
      sp.remove("token");
    }
  }
}
